<template>
  <div style="font-size:15px;font-weight: 600;margin-left: 60px;">{{ '新增订单' }}</div>
  <el-form label-width="110px" style="margin-top: 20px;margin-left: -32px;" :model="dataForm" :rules="rules"
           ref="dataFormRef">
    <div style="margin-left: 64px;margin-top: 20px;">
      <el-form-item label="关联用户" prop="userPhone">
        <el-input v-model="dataForm.userPhone" placeholder="请输入手机号" show-word-limit></el-input>
      </el-form-item>
      <el-button type="primary" @click="getNocUserByPhone()">{{ $t("查询") }}</el-button>
      <el-form-item label="公司名称" prop="company">
        <p>{{dataForm.company}}</p>
      </el-form-item>
      <el-form-item label="产品名称">
        <el-select v-model="dataForm.type" placeholder="请选择" clearable>
          <el-option label="早鸟展会包" value="1"></el-option>
          <el-option label="地区客源包" value="2"></el-option>
          <el-option label="历届展会包" value="4"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="展会时间" v-if="dataForm.type == '4'">
        <el-select v-model="selectedYear" placeholder="请选择时间" style="width: 567px;"
                   @change="fetchExhibitionInfo">
          <el-option v-for="year in availableYears" :key="year" :label="year.year" :value="year.year" />
        </el-select>
      </el-form-item>
      <el-form-item label="展会信息" v-if="dataForm.type == '4'">
        <el-select v-model="selectedExhibitions" multiple collapse-tags collapse-tags-tooltip
                   @change="calculateExhibitionCost" style="width: 567px;" placeholder="请选择展会">
          <!-- 2已购买，1未付款， 0未购买 -->
          <el-option v-for="item in ExhibitList" :key="item.exhibitionName" :disabled="item.isOwn === 2"
                     :label="item.vipContent" :value="item.tid" />
        </el-select>
      </el-form-item>
      <!-- 早鸟展会包 -->
      <el-form-item label="展会信息" v-if="dataForm.type == '1'">
        <el-select v-model="selectedEarlyBirdExhibitions" multiple collapse-tags collapse-tags-tooltip
                   style="width: 567px;" placeholder="请选择展会信息 " @change="calculateExhibitionCost">
          <el-option v-for="item in exhibitionInfo" :key="item.value" :label="item.vipContent"
                     :value="item.tid" />
        </el-select>
      </el-form-item>
      <!-- 地区客源包 -->
      <el-form-item label="地区信息" v-if="dataForm.type == '2'">
        <el-cascader :options="options" v-model="selectedRegion" placeholder="请选择地区" ref="cascaderRef"
                     style="width: 567px;" :props="props1" @change="handleChange" :show-all-levels="false"
                     class="custom-cascader" />
      </el-form-item>


<!--      <div class="form-group file-upload">-->
<!--        <label>附件图片</label>-->
<!--        <input type="file" multiple @change="handleFileUpload" />-->
<!--        <p>支持上传多张图片，大小不超过1M</p>-->
<!--      </div>-->
      <div class="form-item talCost" style="padding-left: 12px;">
        <label>应付费用：</label>
        <span>￥{{ earlyBirdTotalCost }}</span>
      </div>
      <div class="foot">
        <el-button class="quxiao" @click="cancel()">{{ $t("cancel") }}</el-button>
        <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
      </div>
    </div>
  </el-form>
</template>
<script lang="ts" setup>
import baseService from "@/service/baseService";
import { ElMessage } from "element-plus"
import { onMounted, reactive, ref, toRefs } from "vue";
import { useI18n } from "vue-i18n";
import {useRoute, useRouter} from 'vue-router';
import useView from "@/hooks/useView";


const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);

// 存储选中的年份
const selectedYear = ref("");
const options = ref([]);
const selectedRegion = ref([]);
const props1 = {
  checkStrictly: true,
  multiple: true,
  label: 'name',  // 将显示字段改为 name
  value: 'code',   // 将值字段改为 code
  disabled: (data) => data.isOwn === 2 || data.lockFlag == 2

};
// 存储选中的历届展会信息
const selectedExhibitions = ref<string[]>([]);
const ExhibitList = ref<string[]>([]);
// 存储获取到的历届展会信息
const exhibitionInfo = ref<{ value: string; label: string }[]>([]);
// 存储选中的早鸟展会信息
const selectedEarlyBirdExhibitions = ref<string[]>([]);
// 早鸟展会包应付费用
const earlyBirdTotalCost = ref(0);
const vipid = ref([]);
const level = ref([]);
const unlockTime = ref(0);
const visible = ref(false);
const availableYears = ref<string[]>([]);
const dataFormRef = ref();
const vipcode = ref([]);
const dataForm = reactive({
  id: "",
  company: "",
  userPhone:"",
  attrName: "",
  remark: "",
  type:"",
  attrClassifyList: []
});
const route = useRoute();
const id = route.query.id;

// 根据选择的年份请求展会信息
const fetchExhibitionInfo = async () => {
  if (!selectedYear.value) return;
  // 清空之前的选中数据
  selectedExhibitions.value = [];
  // 再获取展会列表
  baseService.post('/noc/vip/queryExhibitionListByYear', {
    year: selectedYear.value
  }).then((res) => {
    if (res.code == 0) {
      ExhibitList.value = res.data || [];  // 存储完整地区数据
    }
  });
};
const fetchYear = async () => {
  baseService.get('/noc/companybasicinfo/queryExhibitionYear', {}).then((res) => {
    if (res.code == 0) {
      availableYears.value = res.data || [];  // 存储完整地区数据
    }
  })
  // 地区信息
  baseService.get('/noc/basearea/getCompanyBasicInfoCity', {}).then((res) => {
    if (res.code == 0) {
      options.value = res.list[0].children || [];  // 存储完整地区数据
    }
  });
  // 早鸟展会信息
  baseService.get('/noc/vip/getZaoniaoBag', {}).then((res) => {
    if (res.code == 0) {
      exhibitionInfo.value = res.data || [];  // 存储完整地区数据
    }
  });
};
//处理地区信息 禁用状态与价格计算
const handleChange = (val) => {
  console.log(val)
  let total = 0;
  let list = 0
  let vipcodes = []
  let vipids = []
  let levels = []

  // 重置所有节点lockFlag
  options.value.forEach(item => {
    if (item && typeof item === 'object') {
      item.lockFlag = 0; // 默认父节点lockFlag=0
      if (Array.isArray(item.children)) {
        item.children.forEach(child => {
          if (child && typeof child === 'object') {
            child.lockFlag = 0; // 默认子节点lockFlag=0
          }
        });
      }
    }
  });

  // 处理选中值
  val.forEach((item) => {
    if (item.length === 1) {
      // 选择父节点: 子节点全部lockFlag=0
      options.value.forEach((parent) => {
        if (parent.code === item[0]) {
          total += parent.vipPrice || 0;
          list += parent.vipCount || 0;
          vipids.push(parent.vipId);
          vipcodes.push(parent.code);
          levels.push("2");

          // 设置所有子节点lockFlag=0
          if (Array.isArray(parent.children)) {
            parent.children.forEach(child => {
              child.lockFlag =2;
            });
          }
        }
      });
    } else if (item.length === 2) {
      // 选择子节点: 父节点lockFlag=2
      options.value.forEach((parent) => {
        if (parent.code === item[0]) {
          parent.lockFlag = 2; // 父节点lockFlag=2

          parent.children.forEach((child) => {
            if (child.code === item[1]) {
              total += child.vipPrice || 0;
              list += child.vipCount || 0;
              vipids.push(child.vipId);
              vipcodes.push(child.code);
              levels.push("3");
              child.lockFlag = 0; // 选中的子节点lockFlag=0
            }
          });
        }
      });
    }
  });

  // 处理取消子节点选择时父节点状态
  options.value.forEach(parent => {
    if (parent.children && Array.isArray(parent.children)) {
      const hasSelectedChild = val.some(item =>
        item.length === 2 && item[0] === parent.code
      );
      if (!hasSelectedChild) {
        parent.lockFlag = 0; // 没有选中子节点时父节点lockFlag=0
      }
    }
  });

  unlockTime.value = list;
  earlyBirdTotalCost.value = total;
  vipid.value = vipids;
  vipcode.value = vipcodes;
  level.value = levels;

}

// 添加历届展会包价格计算方法
const calculateExhibitionCost = () => {
  let total = 0;
  let list = 0
  let vipids = []
  // 遍历选中的展会id，累加对应价格
  if (dataForm.type === "4") {
    selectedExhibitions.value.forEach(id => {
      const exhibition = ExhibitList.value.find(item => item.tid === id);
      if (exhibition) {
        total += exhibition.vipPrice || 0;
        list += exhibition.vipCount || 0;
        vipids.push(exhibition.id);
      }
    });
  } else if (dataForm.type === "1") {
    selectedEarlyBirdExhibitions.value.forEach(id => {
      const exhibition = exhibitionInfo.value.find(item => item.tid === id);
      if (exhibition) {
        total += exhibition.vipPrice || 0;
        list += exhibition.vipCount || 0;
        vipids.push(exhibition.id);
      }
    });
  }

  unlockTime.value = list;
  earlyBirdTotalCost.value = total;
  vipid.value = vipids;
};


const dataFormSubmitHandle = () => {
  // let exhibitionstatus = 0;
  let offline = 0;
  let pan = {}
  if (dataForm.type == "1" || dataForm.type == "4") {
    pan = {
      tid: dataForm.type == "4" ? selectedExhibitions.value.join(',') : selectedEarlyBirdExhibitions.value.join(','),
      unlockTime: unlockTime.value,
      price: earlyBirdTotalCost.value,
      vipId: vipid.value.join(','),
      offline,
      userPhone:dataForm.userPhone

    }
  } else if (dataForm.type == "2") {
    pan = {
      unlockTime: unlockTime.value,
      level: level.value.join(','),
      price: earlyBirdTotalCost.value,
      area: vipcode.value.join(','),
      vipId: vipid.value.join(','),
      offline,
      userPhone:dataForm.userPhone
    }
  }
  console.log(pan)
  baseService.post('/noc/vip/order/save', pan).then((res) => {
    cancel();
    ElMessage.success("新增成功");

  });
};


const rules = ref({
  groupName: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  attrName: [{ required: true, message: t("validate.required"), trigger: "blur" }],
});

const view = reactive({});

const state = reactive({ ...useView(view), ...toRefs(view) });
const router = useRouter();

const cancel = () => {
  router.push('/program/nocorder-list');
  // 关闭当前标签页（需确保useView hook已正确配置）
  state.closeCurrentTab();
};
const getNocUserByPhone = () => {
  baseService.get("/noc/nocuser/getNocUserByPhone/" + dataForm.userPhone).then(res => {
    if (res.code === 0 && res.data) {
      dataForm.company = res.data.company;
    } else {
      ElMessage.error('获取用户信息失败');
    }
  });
};

onMounted(() => {
  // 组件挂载时生成随机颜色
  fetchYear();
});

</script>


<style lang="scss" scoped>
.el-input {
  width: 218px;
  height: 32px;
  opacity: 1;
  border-radius: 5px;
  background: rgba(255, 255, 255, 1);
}

.el-select {
  width: 218px;
  height: 32px;
  opacity: 1;
  border-radius: 5px;
  background: rgba(255, 255, 255, 1);
}

.form {
  display: flex;
  justify-content: space-between;
}

.product-detail-upload {
  margin-top: 10px;
}

.label {
  display: inline-block;
  width: 80px;
  margin-right: 10px;
  text-align: right;
}

.upload-box {
  width: 400px;
  border: 2px dashed #ccc;
  border-radius: 6px;
  background-color: #fafafa;
  text-align: center;
  padding: 20px 0;
  cursor: pointer;
}

.upload-box i {
  font-size: 36px;
  color: #409eff;
}

.el-upload__text {
  display: block;
  margin-top: 10px;
  font-size: 14px;
  color: #666;
}

.el-upload__tip {
  margin-top: 5px;
  font-size: 12px;
  color: #999;
}
.talCost {
  span {
    color: rgba(255, 46, 46, 1);
    padding-right: 20px;
  }
}

.talCost {
  label {
    font-size: 16px;
  }
}
.quxiao {
  border-radius: 5px;
  background: rgba(239, 244, 255, 1);
  color: rgba(22, 119, 255, 1);
  border: 1px solid rgba(22, 119, 255, 1);

}

.foot {
  display: flex;
  justify-content: end;
  position: absolute;
  bottom: 50px;
  right: 50px;

}

.add-button {
  width: 100px;
  height: 32px;
  padding: 10px 20px;
  background-color: rgba(22, 119, 255, 1);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-bottom: 20px;
}

.add-button:hover {
  background-color: rgba(22, 119, 255, 1);
}


.model-item {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.model-select {
  padding: 8px;
  margin-right: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.model-input {
  padding: 8px;
  margin-right: 10px;
  border-radius: 5px;
  width: 218px;
  height: 32px;
  background: rgba(255, 255, 255, 1);
  border: 1px solid rgba(199, 199, 199, 1);
}

.model-input:focus {
  border: 0;
  /* 获得焦点时边框颜色改为蓝色 */
  background: rgba(240, 245, 255, 1);
  color: rgba(22, 119, 255, 1);
  outline: none;
  /* 去除默认的焦点轮廓 */
}

.remove-button {
  padding: 8px 12px;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.quxiao {
  border-radius: 5px;
  background: rgba(239, 244, 255, 1);
  color: rgba(22, 119, 255, 1);
  border: 1px solid rgba(22, 119, 255, 1);
}

.uploaded-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
}
</style>
